package com.jqsoft.launcher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jqsoft.launcher.activity.bean.HBPGuanLi_PersonInfo;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.common.BphsConstants;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.Log;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.jqsoft.launcher.R;

import java.util.ArrayList;
import java.util.List;

public class CeshiActivity extends JQActivity implements OnClickListener,OnScrollListener {
	private final String tag = "CeshiActivity";
	private ListView listview;// 列表
	private ListAdapter adapter;

//	private LinearLayout ll_popup_xuanzhong;
//	private LinearLayout ll_popup_chakan;
//	private LinearLayout ll_popup_quxiao;

	private CheckBox xzCheckbox ,current_xzCheckbox;
//	private PopupWindow popupWindow;
	private Button chaxuan_btn,quick_suifang,totalcount_bt,card_chaxuan_btn;
	private EditText name_et,dangan_num_et,shengfenzheng_et;
	private String content;
	private List<HBPGuanLi_PersonInfo> infoList = new ArrayList<HBPGuanLi_PersonInfo>();
	private boolean notfirstTime=false,isThreadrun=false;
	private long allcount=0;

	private View moreView;
	private LinearLayout progressBar_ll; // 更多等待层
	private Button moreButton;

	private HBPGuanLi_PersonInfo xuanzhong_tiao;
	@Override
	protected int getContentLayout() {

		return R.layout.hbp_diagnosis_layout;
	}

	@Override
	protected void initGui() {
		listview = (ListView) findViewById(R.id.hbp_diagnosis_lv);
		chaxuan_btn=(Button) findViewById(R.id.chaxuan_btn);
		chaxuan_btn.setOnClickListener(CeshiActivity.this);
		quick_suifang=(Button) findViewById(R.id.quick_suifang);
		quick_suifang.setOnClickListener(CeshiActivity.this);
		totalcount_bt=(Button) findViewById(R.id.totalcount_bt);
		dangan_num_et=(EditText) findViewById(R.id.dangan_num_et);
		name_et=(EditText) findViewById(R.id.name_et);
		shengfenzheng_et=(EditText) findViewById(R.id.shengfenzheng_et);
		card_chaxuan_btn=(Button) findViewById(R.id.card_chaxuan_btn);
		card_chaxuan_btn.setOnClickListener(CeshiActivity.this);
	}

	@Override
	protected void initAction() {
		setGoBack();
		listview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// PopupWindow popupWindow = new
				// PopupWindow(AppManagerActivity.this);
				HBPGuanLi_PersonInfo obj = (HBPGuanLi_PersonInfo) listview.getItemAtPosition(position);
//				if (obj instanceof HBPGuanLi_PersonInfo) {
					xuanzhong_tiao= obj;

				for(int i=0;i<infoList.size();i++){
					infoList.get(i).setCheck(false);
				}
				obj.setCheck(true);
				if(current_xzCheckbox!=null){
					current_xzCheckbox.setChecked(false);}
					xzCheckbox.setChecked(true);
					current_xzCheckbox=xzCheckbox;
					adapter.notifyDataSetChanged();
			}

		});

		listview.setOnScrollListener(this);

	}

	@Override
	protected void initData() {
		setTitle("测试功能");
		if(BphsConstants.sAndroidReader){
			chaxuan_btn.setText("读身份证查询");
			dangan_num_et.setEnabled(false);
			name_et.setEnabled(false);
			shengfenzheng_et.setEnabled(false);
			dangan_num_et.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_grayall_corner));
			name_et.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_grayall_corner));
			shengfenzheng_et.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_grayall_corner));
		}
		moreView = getLayoutInflater().inflate(
				R.layout.finance_fund_pagination_more, null);
		moreButton = (Button) moreView.findViewById(R.id.loadMore);
		moreButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			      if(notfirstTime&&(allcount>infoList.size())&&!isThreadrun)
			        {
			    	  moreButton.setVisibility(View.GONE);
			    	  progressBar_ll.setVisibility(View.VISIBLE);
			    	  new Thread(sendable).start();
			        }
			}
		});
		progressBar_ll = (LinearLayout) moreView.findViewById(R.id.progressBar_ll);

	}
	 @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		 dismissrogressBar();
	    	if(data!=null){
	    	 String cardName =	data.getStringExtra("cardName");
	    	 String cardNumber =	data.getStringExtra("cardNumber");
	    	 if(requestCode==1){
	    		 if(StringUtils.isNotBlank(cardName)&&
	    					StringUtils.isNotBlank(cardNumber)){
	    				name_et.setText(cardName);
	    				shengfenzheng_et.setText(cardNumber);
	    				if(infoList.size()>0){
	    					listview.removeFooterView(moreView);}
	    					infoList.clear();
	    					allcount=0;
	    					notfirstTime=false;
	    					loadWaitPanel();
	    					new Thread(sendable).start();
	    				}else{
	    			    	Toast.makeText(this, "读身份证信息失败", 000).show();
	    				}
	    			}
	    	}else{
	    		Toast.makeText(this, "读身份证信息失败", 0).show();
	    	}
	    	super.onActivityResult(requestCode, resultCode, data);
	    }



	private Handler myhandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.MSG_LOAD_OVER:
				adapter = new ListAdapter();
				notfirstTime=true;
				if(!(infoList.size()==allcount||allcount==0||infoList.size()<=0)){
//					listview.removeFooterView(moreView);
					listview.addFooterView(moreView);
				}
				listview.setAdapter(adapter);
				String count="共计"+allcount+"条）";
				totalcount_bt.setText("（已加载"+infoList.size()+"条/"+count);
				dismissrogressBar();
				break;
			case Constant.SHOW_UPDATE:
				totalcount_bt.setText("（已加载"+infoList.size()+"条/"+"共计"+allcount+"条）");
				if(infoList.size()>=allcount){
					 listview.removeFooterView(moreView);
				}else{
					progressBar_ll.setVisibility(View.GONE);
			    	  moreButton.setVisibility(View.VISIBLE);
				}
				adapter.notifyDataSetChanged();

//					dismissrogressBar();


				break;
			}
			isThreadrun=false;
		}
	};
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
//		   dismissPopupWindow();
		      if(firstVisibleItem+visibleItemCount==totalItemCount&&notfirstTime&&(allcount>infoList.size())&&!isThreadrun)
		        {
//		    	  loadWaitPanel();
//		        	//开线程去下载网络数据
//		    	  new Thread(sendable).start();
		        }
			}
	// 请求服务器
			private Runnable sendable = new Runnable() {

				public void run() {
					isThreadrun=true;
					 String requestUrl = BphsURL.getCommonPath("TEST_URL");
					Log.i(tag, "查询:content" + requestUrl);
					String methodName= BphsURL.getCommonPath("TEST_METHOD");
					JSONObject data = new JSONObject();
//					{"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10","sPersonName":"陈艳林","sCardNo":"340824195312281418"}
					try {
						UserLoginInfo info = UserLoginInfo.getInstances();
						data.put("sAreaCode", info.getsManagementDivisionCode());//
						data.put("iCurrentPageIndex", "1");
						data.put("iPageSize", "10"); //
						data.put("sNo", dangan_num_et.getText()); //
						data.put("sPersonName", "陈艳林"); //
						data.put("sCardNo", "340824195312281418"); //
//						data.put("sPersonName", name_et.getText()); //
//						data.put("sCardNo", shengfenzheng_et.getText()); //
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					content = WebServiceUtils.requestByParams(methodName, data.toString(), requestUrl);
					if (StringUtils.isNotBlank(content)) {
						  try {
								Log.i(tag, "返回的查询结果"+content);
//							 String result= content.replaceAll("\\\\", "");
//								Log.i(tag, "返回的查询结果"+result);
							JSONObject json = new JSONObject(content);
//							Log.i(tag, "返回的查询结果"+result);"AllCount":0,
//							allcount= 28;
							allcount= json.getLong("AllCount");
						JSONObject jo = new JSONObject(json.getString("Data"));
						 JSONArray jsonArray = (JSONArray) jo.get("Table");
				            for (int i = 0; i < jsonArray.length(); ++i) {
				                JSONObject o = (JSONObject) jsonArray.get(i);
				                HBPGuanLi_PersonInfo info =new HBPGuanLi_PersonInfo(o.getString("sPersonID"),o.getString("sNo"), o.getString("sPersonName"), o.getString("sSexName"),
				                		o.getString("dBirthday"),o.getString("sCardNo"),o.getString("sGradeName"),o.getString("sDiagnosedHospital"),
				                		o.getString("dDiagnosedTime"),o.getString("sInputDeptName"),o.getString("VisitingCount"),
				                		o.getString("HealthyCheckUpCount"),
				                		o.getString("iState"),o.getString("sAreaCode")
				                		,o.getString("sphoto"));
				                if(allcount==1){
				                	info.setCheck(true);
				                	xuanzhong_tiao=info;
				                }
				    			infoList.add(info);
				            }} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						  if(notfirstTime){
							  myhandler.sendEmptyMessage(Constant.SHOW_UPDATE);
						  }else{
						myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);}
					}
				}
			};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.chaxuan_btn://查询按钮
			if(!BphsConstants.sAndroidReader){
			if(infoList.size()>0){
			listview.removeFooterView(moreView);}
			infoList.clear();
			allcount=0;
			notfirstTime=false;
			loadWaitPanel();
			new Thread(sendable).start();}else{
				loadWaitPanel();
				Intent intent = new Intent(this,TestJarActivity.class);
		    	startActivityForResult(intent, 1);
			}
			return;
		case R.id.quick_suifang://随访按钮
			if(current_xzCheckbox==null&&infoList.size()>1){
				MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
				return;
			}
			if(xuanzhong_tiao!=null){
			Intent intent =new Intent(act, CeshiFollowUpActivity.class);
			  Bundle bundle = new Bundle();
			  bundle.putSerializable("HBPGuanLi_PersonInfo",  xuanzhong_tiao);
			  intent.putExtras(bundle);
   	          startActivity(intent);}else{
			toNoFinish(CeshiFollowUpActivity.class);}
			return;
		case R.id.ll_popup_xuanzhong:
			if(current_xzCheckbox!=null){
			current_xzCheckbox.setChecked(false);}
			xzCheckbox.setChecked(true);
			current_xzCheckbox=xzCheckbox;
			break;
		case R.id.ll_popup_chakan:
//			toNoFinish(HBPCheckListActivity.class);
			break;
		case R.id.card_chaxuan_btn:
			Intent intent = new Intent(this,TestJarActivity.class);
	    	startActivityForResult(intent, 1);
			return;
		}
//		dismissPopupWindow();
	}
		
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d(tag, "屏蔽 home,back,menu键keyCode:" + keyCode);
		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			if (popupWindow != null && popupWindow.isShowing()) {
//				popupWindow.dismiss();
//				popupWindow = null;
//				return true;
//			}
			Log.d(tag, "BACK键捕获。to BACK");
			act.finish();
			act.overridePendingTransition(android.R.anim.slide_in_left,
					android.R.anim.slide_out_right);
			return true;
		}
		if (KeyEvent.KEYCODE_HOME == keyCode) {
//			if (popupWindow != null && popupWindow.isShowing()) {
//				popupWindow.dismiss();
//				popupWindow = null;
//				return true;
//			}
			Log.d(tag, "home键捕获。to home");
			toHome();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public void onDestroy() {
//		dismissPopupWindow();
		super.onDestroy();
	}
//	关闭pop窗口
//	private void dismissPopupWindow() {
//		if (popupWindow != null && popupWindow.isShowing()) {
//			popupWindow.dismiss();
//			popupWindow = null;
//		}
//	}

	private class ListAdapter extends BaseAdapter {

		public int getCount() {
//			Log.d(tag, "列表的大小" + functionList.size());
//			return functionList.size();
			return infoList.size();
		}

		public Object getItem(int position) {
//			return functionList.get(position);
			return infoList.get(position);
		}

		public long getItemId(int position) {

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
//			ViewHolder holder;
			LayoutInflater inflater = LayoutInflater.from(act);
//			if (convertView == null) {
//				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.hbp_diagnosis_item, null);
//				holder.iv_function_icon = (ImageView) convertView
//						.findViewById(R.id.iv_function_icon);
				TextView dangan_num_tv = (TextView) convertView
						.findViewById(R.id.dangan_num_tv);
				TextView name_tv = (TextView) convertView
						.findViewById(R.id.name_tv);
				TextView sex_tv = (TextView) convertView
						.findViewById(R.id.sex_tv);
				TextView age_tv = (TextView) convertView
						.findViewById(R.id.age_tv);
				TextView shengfenzheng_tv = (TextView) convertView
						.findViewById(R.id.shengfenzheng_tv);
				TextView jibie_tv = (TextView) convertView
						.findViewById(R.id.jibie_tv);
				TextView quezheng_yiyuan_tv = (TextView) convertView
						.findViewById(R.id.quezheng_yiyuan_tv);
				TextView quezheng_date_tv = (TextView) convertView
						.findViewById(R.id.quezheng_date_tv);
//				holder.luru_danwei_tv = (TextView) convertView
//						.findViewById(R.id.luru_danwei_tv);
				TextView suifang_cishu_tv = (TextView) convertView
						.findViewById(R.id.suifang_cishu_tv);
//				holder.tijian_cishu_tv = (TextView) convertView
//						.findViewById(R.id.tijian_cishu_tv);
//				holder.shifou_guanli_tv = (TextView) convertView
//						.findViewById(R.id.shifou_guanli_tv);
//				convertView.setTag(holder);
				CheckBox cb= (CheckBox) convertView
						.findViewById(R.id.xuanzhong_cb);
//			} else {
//				holder = (ViewHolder) convertView.getTag();
//			}
				
			dangan_num_tv.setText(infoList.get(position)
					.getsNo());
			name_tv.setText(infoList.get(position)
					.getsPersonName());
			sex_tv.setText(infoList.get(position)
					.getsSexName());
			
			age_tv.setText(CommonUtil.calcAge2(infoList.get(position)
					.getdBirthday())+"");
			shengfenzheng_tv.setText(infoList.get(position)
					.getsCardNo());
			jibie_tv.setText(infoList.get(position)
					.getsGradeName());
			quezheng_yiyuan_tv.setText(infoList.get(position)
					.getsDiagnosedHospital());
			quezheng_date_tv.setText(CommonUtil.String2date(infoList.get(position)
					.getdDiagnosedTime()));
//			holder.luru_danwei_tv.setText(infoList.get(position)
//					.getsInputDeptName());
			suifang_cishu_tv.setText(infoList.get(position)
					.getVisitingCount());
//			holder.tijian_cishu_tv.setText(infoList.get(position)
//					.getHealthyCheckUpCount());
//			holder.shifou_guanli_tv.setText("-1".equals(infoList.get(position)
//					.getiState())?"否":"是");
			cb.setChecked(infoList.get(position)
					.isCheck());
			return convertView;
		}
	}
}
